﻿using Serilog;
using EWms.Core.Components;
using EWms.WebApi.Filter;

namespace EWms.WebApi;

public static class ApiSetup
{
    /// <summary>
    /// 配置服务
    /// </summary>
    /// <param name="builder"></param>
    public static void AddServices(this WebApplicationBuilder builder)
    {
        //进行配置注册 | 添加静态文件读取(优先级比较高)
        AppSettings.Initialize(builder.Configuration);
        var jwt = AppSettings.Jwt;
        var redis = AppSettings.Redis;

        builder.WebHost.UseUrls(AppSettings.SelfUrl);

        builder.Host.UseSerilog();

        builder.Services.AddJsonOptionSetup();

        builder.Services.AddControllers();

        builder.Services.AddEndpointsApiExplorer();

        builder.Services.AddCorsSetup();

        builder.Services.AddJwt();

        builder.Services.AddSwagger();

        // 添加sqlsugar
        builder.Services.AddSqlsugarSetup();

        builder.Services.AddMvc(option =>
        {
            option.Filters.Add(typeof(ResultFilterAttribute));
            option.Filters.Add(typeof(ApiExceptionAttribute));
        });
    }

    /// <summary>
    /// 配置 HTTP 请求管道
    /// </summary>
    /// <param name="app"></param>
    public static void UseMiddlewares(this WebApplication app)
    {
        if (app.Environment.IsDevelopment())
        {
            app.AddSwagger();
        }

        app.UseHttpsRedirection();

        app.UseAuthentication();
        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
}
